package com.gensdai.leliang.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/27.
 */

public class BindingMail extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.next_wave)
    TextView next_wave;
    @BindView(R.id.ui_title)
    TextView ui_title;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.user_phone)
    EditText userPhone; // 邮箱
    @BindView(R.id.auth_code)
    EditText authCode; // 验证码
    @BindView(R.id.time)
    TextView time; //获取短信
    @BindView(R.id.sure)
    TextView sure;
    @BindView(R.id.tishi)
    LinearLayout tishi;

    private Upload up;
    UserNameBean user;
    SharedPreferences share;
    SharedPreferences.Editor ed;
    private int surplus_time = 60;
    private boolean get_note = true;

    private final int ENTER = 1;// 检验验证码
    private final int TIME = 2;// 获取验证码
    private final int SEND = 3;// 获取验证码
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            BindingMail.this.finish();
                        }
                        Toast.makeText(
                                BindingMail.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case TIME:
                    if (surplus_time == 0) {
                        time.setText(getResources().getString(R.string.get_auth_code));
                        surplus_time = 60;
                        get_note = true;
                    } else {
                        surplus_time--;
                        time.setText(surplus_time + " s");
                        handler.sendEmptyMessageDelayed(TIME, 1000);
                    }
                    break;
                case SEND:
                    up.dismiss();
                    try {
                        Toast.makeText(
                                BindingMail.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.binding_mail);
        ButterKnife.bind(this);
        init();
        setonclick();

    }

    /**
     * 设置事件
     */
    private void setonclick() {
        next_wave.setOnClickListener(this);
        back.setOnClickListener(this);
        time.setOnClickListener(this);
        sure.setOnClickListener(this);
    }

    /**
     * 初始化
     */
    private void init() {
        ui_title.setText("绑定邮箱");
        share = getSharedPreferences("User", MODE_PRIVATE);
        up = new Upload(this);
        ed = share.edit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next_wave:
                if (!isEmail(userPhone.getText().toString())) {
                    Toast.makeText(this, "请输入正确的邮箱!~", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(authCode.getText().toString().trim())) {
                    Toast.makeText(this, "请输入正确验证码!~", Toast.LENGTH_SHORT).show();
                    return;
                }
                Check_UnputCode();
                break;
            case R.id.back:
                BindingMail.this.finish();
                break;
            case R.id.time:
                if (!isEmail(userPhone.getText().toString())) {
                    Toast.makeText(this, "请输入正确的邮箱!~", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (get_note) {
                    sendChecCode();
                    handler.sendEmptyMessageDelayed(TIME, 1000);
                    get_note = false;
                    next_wave.setVisibility(View.GONE);
                    tishi.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.sure:
                next_wave.setVisibility(View.VISIBLE);
                tishi.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 检验验证码
     */
    private void Check_UnputCode() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("email", userPhone.getText().toString().trim()); //邮箱
        loginParams.put("userNo", share.getString("userno", "")); //
        loginParams.put("emailCode", authCode.getText().toString().trim()); //验证码
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).PERSONAL_CHECK_EMAIL_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 发送验证码
     */
    private void sendChecCode() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("email", userPhone.getText().toString().trim()); //邮箱
        send(loginParams);
    }

    //返回字符串类型
    private void send(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).PERSONAL_BIND_EMAIL_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = SEND;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    //判断email格式是否正确
    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

}
